<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Java内存模型 | Reality</title><meta name="keywords" content="JMM"><meta name="author" content="dtyy"><meta name="copyright" content="dtyy"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Java内存模型何为底层原理？底层原理是指从Java代码到CPU指令的执行过程。  Java源代码，通过javac编译成字节码文件；JVM执行字节码文件，并将字节码文件转化为机器指令；机器指令可以在CPU上直接运行，即最终的程序执行。 为什么需要JMM，什么是JMM不同CPU的机器指令不同，不同的JVM也有着不同的翻译。  多线程出现的最主要的目的就是提高CPU的利用率，提高处理速度，避免无效等待">
<meta property="og:type" content="article">
<meta property="og:title" content="Java内存模型">
<meta property="og:url" content="https://dtyytop.gitee.io/2020/04/15/devnotes/zhi-mian-java/bing-fa/bing-fa-he-xin/2.1-java-nei-cun-mo-xing-yu-san-da-te-xing/index.html">
<meta property="og:site_name" content="Reality">
<meta property="og:description" content="Java内存模型何为底层原理？底层原理是指从Java代码到CPU指令的执行过程。  Java源代码，通过javac编译成字节码文件；JVM执行字节码文件，并将字节码文件转化为机器指令；机器指令可以在CPU上直接运行，即最终的程序执行。 为什么需要JMM，什么是JMM不同CPU的机器指令不同，不同的JVM也有着不同的翻译。  多线程出现的最主要的目的就是提高CPU的利用率，提高处理速度，避免无效等待">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222621.jpg">
<meta property="article:published_time" content="2020-04-15T15:28:04.000Z">
<meta property="article:modified_time" content="2021-05-25T23:47:54.203Z">
<meta property="article:author" content="dtyy">
<meta property="article:tag" content="JMM">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222621.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://dtyytop.gitee.io/2020/04/15/devnotes/zhi-mian-java/bing-fa/bing-fa-he-xin/2.1-java-nei-cun-mo-xing-yu-san-da-te-xing/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"prismjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: true
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: dtyy","link":"链接: ","source":"来源: Reality","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Java内存模型',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-05-26 07:47:54'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Reality" type="application/atom+xml">

<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">95</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/gallery/"><i class="fa-fw fas fa-images"></i><span> 图片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222621.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Reality</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/gallery/"><i class="fa-fw fas fa-images"></i><span> 图片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Java内存模型</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-04-15T15:28:04.000Z" title="发表于 2020-04-15 23:28:04">2020-04-15</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-05-25T23:47:54.203Z" title="更新于 2021-05-26 07:47:54">2021-05-26</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/">并发编程</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/Java%E5%86%85%E5%AD%98%E6%A8%A1%E5%9E%8B/">Java内存模型</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>11分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Java内存模型"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="Java内存模型"><a href="#Java内存模型" class="headerlink" title="Java内存模型"></a>Java内存模型</h2><h3 id="何为底层原理？"><a href="#何为底层原理？" class="headerlink" title="何为底层原理？"></a>何为底层原理？</h3><p>底层原理是指从Java代码到CPU指令的执行过程。</p>
<p><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210518073536.png" alt="img"></p>
<p>Java源代码，通过javac编译成字节码文件；JVM执行字节码文件，并将字节码文件转化为机器指令；机器指令可以在CPU上直接运行，即最终的程序执行。</p>
<h3 id="为什么需要JMM，什么是JMM"><a href="#为什么需要JMM，什么是JMM" class="headerlink" title="为什么需要JMM，什么是JMM"></a>为什么需要JMM，什么是JMM</h3><p>不同CPU的机器指令不同，不同的JVM也有着不同的翻译。</p>
<ul>
<li>多线程出现的最主要的目的就是提高CPU的利用率，提高处理速度，避免无效等待，例如IO，而高速缓存的出现是为了缓解CPU与内存之间速度不匹配的问题。多处理器系统，每个处理器都有着自己的高级缓存，并共享着同一主内存，处理器本地缓存对其他处理器不可见，存在缓存一致性问题。</li>
<li>处理器为了提高运算速度，可能会对输入代码进行乱序执行优化，在计算之后将乱序执行的结果重组。保证结果与顺序执行结果一致，但不保证程序语句执行顺序与代码顺序一致。</li>
<li>JVM的即时编译器也会执行指令重排序优化。编译器生成的指令顺序可以与源代码顺序不同，编译器还会把变量保存在寄存器中，而不是内存中。</li>
</ul>
<p>程序运行的结果可能会与预期不同。</p>
<p>Java内存模型作为规范，规定JVM必须遵循一组最小保证，即对变量的写入操作在什么时候对其他线程可见。通过JMM，屏蔽各种硬件和操作系统的差异，使Java程序在不同的平台上有着一致的内存访问效果。</p>
<p>除此之外，JMM是工具类和关键字的原理</p>
<ul>
<li>volatile、synchronized、Lock等底层原理都是JMM</li>
<li>内存栅栏，是CPU或者编译器在对内存随机访问操作的一个同步点，用于对共享数据操作时做额外保证。因为有Java内存模型，JVM通过在适当的位置插入内存栅栏来屏蔽JVM与底层平台之间的差异，开发人员只需要用同步工具和关键字开发并发程序即可。</li>
</ul>
<h3 id="概念区分：JVM内存结构、JMM、Java对象模型"><a href="#概念区分：JVM内存结构、JMM、Java对象模型" class="headerlink" title="概念区分：JVM内存结构、JMM、Java对象模型"></a>概念区分：JVM内存结构、JMM、Java对象模型</h3><p>JVM内存结构，与Java虚拟机的运行时区域相关；【后续学习】</p>
<p>Java内存模型，与Java并发编程有关；</p>
<p>Java对象模型，和Java对象在虚拟机中的表现形式有关。【后续学习】</p>
<h2 id="重排序"><a href="#重排序" class="headerlink" title="重排序"></a>重排序</h2><h3 id="重排序案例演示"><a href="#重排序案例演示" class="headerlink" title="重排序案例演示"></a>重排序案例演示</h3><p>线程内部代码实际执行顺序与源代码顺序不一致。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">OutOfOrderExecution</span> <span class="token punctuation">{</span>
    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">int</span> x <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">,</span> y <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">int</span> a <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">,</span> b <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">{</span>
            <span class="token class-name">Thread</span> thread1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token punctuation">{</span>
                a <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
                x <span class="token operator">=</span> b<span class="token punctuation">;</span>
            <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">Thread</span> thread2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token punctuation">{</span>
                b <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
                y <span class="token operator">=</span> a<span class="token punctuation">;</span>
            <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            thread1<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            thread2<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            thread1<span class="token punctuation">.</span><span class="token function">join</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            thread2<span class="token punctuation">.</span><span class="token function">join</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"第"</span> <span class="token operator">+</span> i <span class="token operator">+</span> <span class="token string">"次，x = "</span> <span class="token operator">+</span> x <span class="token operator">+</span> <span class="token string">",y = "</span> <span class="token operator">+</span> y<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>对于上面的代码，如果每个线程中代码实际运行顺序与代码顺序一致，可能有下面3种情况：</p>
<pre class="line-numbers language-none"><code class="language-none">a = 1; x = b(0); b = 1, y = a(1) ==&gt; (0, 1)
b = 1; y = a(0); a = 1, x = b(1) ==&gt; (1, 0)
a = 1; b = 1; x = b(1); y = a(1) ==&gt; (1, 1)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>实际运行中，还有另一种情况(0, 0)。可能有两种原因导致这个情况出现：（1）线程1或线程2中两行赋值代码存在重排序；（2）由可见性问题导致的表面重排序。</p>
<pre class="line-numbers language-none"><code class="language-none">// 线程1重排序
x = b(0); b = 1; y = a(0); a = 1; ==&gt;(0, 0) 
// 可见性
a = 1; b = 1; x = b(0); y = a(0) ==&gt; (0, 0)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="重排序的好处"><a href="#重排序的好处" class="headerlink" title="重排序的好处"></a>重排序的好处</h3><p>重排序可以减少CPU执行的指令数量，提高处理速度。</p>
<p><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210518075616.png" alt="img"></p>
<p><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210518075625.png" alt="img"></p>
<h3 id="重排序的3种情况"><a href="#重排序的3种情况" class="headerlink" title="重排序的3种情况"></a>重排序的3种情况</h3><ol>
<li><p>编译器优化——编译器包括JVM、JIT编译器等，出于优化的目的，在编译过程中会进行一定程度的重排序，导致生成的机器指令和之前的字节码顺序不一致。在上面的例子中，由于a = 1和x = b两行语句没有数据依赖关系，编译器可能互换两者顺序。</p>
</li>
<li><p>CPU指令重排序——就算编译器不发生重排序，CPU也可能进行指令重排。</p>
</li>
<li><p>内存的“重排序”：内存系统内不存在重排序，但可能带来与重排序一样的效果。由于内存有缓存的存在，在JMM中表现为主内存和本地内存，主内存和本地内存不一致，会使程序表现为乱序。在上面的例子中，可能线程1和线程2都分别修改了a和b的值，但修改没有先回到主内存中，线程1看到b的值仍然是0。</p>
</li>
</ol>
<h2 id="可见性"><a href="#可见性" class="headerlink" title="可见性"></a>可见性</h2><h3 id="可见性演示案例"><a href="#可见性演示案例" class="headerlink" title="可见性演示案例"></a>可见性演示案例</h3><p>线程1执行修改操作，线程2执行打印操作。</p>
<pre class="line-numbers language-none"><code class="language-none">public class FieldVisibility {
    private int a = 1;
    private int b = 2;

    private void print() {
        System.out.println("b = " + b + ", a = " + a);
    }

    private void update() {
        a = 3;
        b = a;
    }
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>仍然手动分析可能出现的情况</p>
<pre class="line-numbers language-none"><code class="language-none">b = 2, a = 1 // 线程2先执行完毕
b = 2, a = 3 // a=3, 然后print操作
b = 3, a = 3 // 线程1先执行完毕
b = 3, a = 1 // 可见性导致的特殊情况！！！<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>update方法中两行代码有数据依赖，不存在重排序等情况。按正常思考，仅按代码层面思考，b的值为3，a的值必然也会是3。b=3，a=1，说明线程1对a的修改仍未刷新到主内存，对线程2不可见。对a和b变量使用volatile关键字修改，保证其可见性，便不会出现b=3,a=1的情况了。</p>
<p>println打印是非原子操作，在打印完a后，仍可能存在线程切换，不能单纯的证明可见性。</p>
<p><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210519000935.png" alt="img"></p>
<h3 id="为什么有可见性问题"><a href="#为什么有可见性问题" class="headerlink" title="为什么有可见性问题"></a>为什么有可见性问题</h3><p>CPU有多级缓存，导致读的数据过期。</p>
<ul>
<li>高速缓存的容量比主存小，但速度仅次于寄存器，所以CPU与主内存之间加了Cache层。</li>
<li>线程之间对于共享变量的不可见，不是直接有多核引起的，而是由多缓存引起的。如果所有核心都使用同一个缓存时，也不存在内存可见性问题。</li>
<li>每个核心都会将自己需要的数据读取到独占缓存中，然后将修改写入缓存，等待写回到主内存中。这个过程可能导致使用其他核心的线程读取到过期的数据。</li>
</ul>
<h3 id="保证可见性的措施"><a href="#保证可见性的措施" class="headerlink" title="保证可见性的措施"></a>保证可见性的措施</h3><p>具备可见性的关键字有3个：</p>
<ul>
<li>volatile：<u>volatile修饰的变量赋值时，会将值直接刷新回主内存。</u></li>
<li>synchronized：<u>对一个变量的unlock操作之前，必须把该变量同步会主内存。</u></li>
<li>final：被final修饰的字段在构造器中一旦初始化完成，并且在构造器中没有将this引用传递出去，那么其他线程都能看到final字段值。</li>
</ul>
<p>其他可见性措施，例如Lock、Thread.join()、Thread.start()、并发工具等，具体参考happens-before的8大原则。</p>
<h2 id="JMM的抽象"><a href="#JMM的抽象" class="headerlink" title="JMM的抽象"></a>JMM的抽象</h2><h3 id="操作对象–共享变量"><a href="#操作对象–共享变量" class="headerlink" title="操作对象–共享变量"></a>操作对象–共享变量</h3><p>JMM定义变量的内存访问规则。<strong>共享变量指的是成员变量、静态变量，不包括成员变量和方法参数。</strong></p>
<h3 id="什么是本地内存"><a href="#什么是本地内存" class="headerlink" title="什么是本地内存"></a>什么是本地内存</h3><p>Java作为高级语言，使用JMM定义了一套读写内存数据的规范，JVM屏蔽了CPU多层缓存这些底层细节。虽然不再需要关心一级、二级缓存等，但是JMM抽象出了主内存和本地内存的概念。<u>本地内存不是真的给每个线程分配内存，而是JMM的一个抽象，对寄存器、多级缓存、硬件和编译器优化等的抽象。</u></p>
<img src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210519001425.png" alt="img" style="zoom:50%;">

<h3 id="主内存和本地内存的关系"><a href="#主内存和本地内存的关系" class="headerlink" title="主内存和本地内存的关系"></a>主内存和本地内存的关系</h3><p>JMM规范有如下规定</p>
<ul>
<li>所有共享变量存储在主内存中，同时每个线程都有着自己独立的工作内存，工作内存的变量是主内存的拷贝。</li>
<li>线程只能操作工作内存中的变量，再同步到主内存中，而不能直接读写主内存中的变量。</li>
<li>主内存是多个线程共享的，而线程之间不共享工作内存。线程之间读写共享数据，需要借助主内存中转来完成。</li>
</ul>
<h3 id="内存交互操作（了解）"><a href="#内存交互操作（了解）" class="headerlink" title="内存交互操作（了解）"></a>内存交互操作（了解）</h3><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210519001554.jpg" alt="img" style="zoom:50%;">

<p>8种操作</p>
<p>lock：锁定，作用于主内存变量，将变量标识为线程独占状态。</p>
<p>read：读取，作用于主内存变量，将变量值从主内存读取到线程工作内存中。</p>
<p>load：载入，作用于工作内存变量，将read传来的变量值放入到工作内存的变量副本中。</p>
<p>use：使用，作用于工作内存变量，线程执行将值传递给执行引擎。</p>
<p>assign：赋值，作用于工作内存变量，线程执行结束将值赋给工作内存变量。</p>
<p>store：存储，作用于工作内存变量，将变量值共工作内存传递到主内存。</p>
<p>write：写入，作用于主内存变量，将store传来的变量值放到主内存变量中。</p>
<p>unlock：解锁，作用于主内存变量，释放锁定状态变量，解锁后可被其他线程锁定。</p>
<p>8项规则</p>
<p>\1. read和load、store和write各操作不能单独出现。</p>
<p>\2. 线程不能丢弃assign操作。工作内存中变量发生了改变，必须同步到主内存。</p>
<p>\3. 如果没有发生assign操作，工作内存中的数据不能同步到主内存。</p>
<p>\4. 新的变量只能在主内存中产生，不允许在工作内存中使用未初始化的变量。</p>
<p>\5. 一个变量在同一时刻只能被一个线程锁定lock，可以lock多次，但需要unlock相同次数。</p>
<p>\6. 对一个变量执行lock操作，会清空工作内存中变量的值。在use前，重新执行load或assign操作初始化变量值。</p>
<p>\7. 变量未被锁定，不能被解锁。</p>
<p>\8. 对变量解锁前，需要将变量同步到主内存。</p>
<h3 id="happens-before原则"><a href="#happens-before原则" class="headerlink" title="happens-before原则"></a>happens-before原则</h3><p>happens-before原则是保证一个线程执行的动作对不同线程中的另一个动作可见。</p>
<p>happens-before不仅保证在”时间”上动作的先后顺序，还保证了对内存的读写顺序，避免内存一致性错误。</p>
<p>【特别注意】先行发生不是指时间上先发生，而是指操作可见。A先发生于B，那么B一定能看到A的执行，并不是A比B早发生。</p>
<p>上面的可见性演示，存在b=3,a=1的情形。b=a被赋值为3，而a的值仍为1，不符合happens-before原则；加上volatile，便满足原则，线程1的修改对线程2可见（b为3时，a也必然为3）。</p>
<h4 id="具体原则（先发生，可见）"><a href="#具体原则（先发生，可见）" class="headerlink" title="具体原则（先发生，可见）"></a>具体原则（先发生，可见）</h4><ol>
<li>单线程原则：对于一个线程，书写在前面的操作先于后面的操作执行。</li>
</ol>
<p>时间先后顺序与happens-before没有关系。例如下面的代码，编译器可能会进行指令重排序</p>
<pre class="line-numbers language-none"><code class="language-none">int i = 1;
int j = 2;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<ol start="2">
<li><p>锁原则：对于同一个锁，解锁操作先于加锁操作执行。</p>
</li>
<li><p>volatile原则：volatile字段的写入操作先于对该字段的读操作。volatile字段的写入/读取操作，和进入/退出同步代码块有着相似的内存一致性效果，但是不需要获取监视器/锁。</p>
</li>
<li><p>线程启动：线程对象的start方法先于线程中的run操作。</p>
</li>
<li><p>线程终止：线程的所有操作先于线程的join方法（终止检测）。</p>
</li>
<li><p>线程中断：线程中断interrupt()方法的调用先于该线程检测到中断事件。</p>
</li>
<li><p>线程结束：对象初始化完成，先于其finalize()方法的调用。</p>
</li>
<li><p>传递性：A先于B，B先于C，则A先于C。</p>
</li>
<li><p>工具类中的happens-before原则，例如线程安全的容器，get操作一定能看到之前put的操作；CountDownLatch的countDown操作也必然在await操作之前。</p>
</li>
</ol>
<p>继续分析上面字段可见性演示案例：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">FieldVisibility</span> <span class="token punctuation">{</span>
    <span class="token keyword">private</span> <span class="token keyword">int</span> a <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">volatile</span> <span class="token keyword">int</span> b <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">print</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"b = "</span> <span class="token operator">+</span> b <span class="token operator">+</span> <span class="token string">", a = "</span> <span class="token operator">+</span> a<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">update</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        a <span class="token operator">=</span> <span class="token number">3</span><span class="token punctuation">;</span>
        b <span class="token operator">=</span> a<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>通过之前的分析，给a和b加上volatile关键字，可以保证可见性。实际上只给b加即可。b之前的写入（b = a)对读取b的代码（print b)都可见，因此写线程对a的赋值对读线程可见。根据happens-before原则保证了a的值必为3。</p>
<h2 id="原子性"><a href="#原子性" class="headerlink" title="原子性"></a>原子性</h2><p>一系列操作，要么全部执行成功，要么全部不执行。i++包含三个操作。</p>
<h3 id="java中的原子操作有哪些？"><a href="#java中的原子操作有哪些？" class="headerlink" title="java中的原子操作有哪些？"></a>java中的原子操作有哪些？</h3><p>1、<strong>除了long和double值之外的基本类型的赋值操作</strong> </p>
<p>2、<strong>所有引用reference的赋值操作</strong></p>
<p>3、java.concurrent.Atomic.* 包中所有类的原子操作（原子类）</p>
<p>其他并发操作需要额外同步</p>
<p><a target="_blank" rel="noopener" href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html">https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html</a></p>
<h3 id="long和double的原子性"><a href="#long和double的原子性" class="headerlink" title="long和double的原子性"></a>long和double的原子性</h3><p>Java对64位long和double写入分为两次32位写入。可能会导致线程分别看到值的前32位和后32位。</p>
<p>volatile long和double值的写入和读取必然是原子的。在实际开发中，对于long和double值可以不加volatile修饰，因为商用Java虚拟机已经保证了其原子性。</p>
<h3 id="原子操作与原子操作的组合，并不一定是原子操作，例如存在竞态条件。"><a href="#原子操作与原子操作的组合，并不一定是原子操作，例如存在竞态条件。" class="headerlink" title="原子操作与原子操作的组合，并不一定是原子操作，例如存在竞态条件。"></a>原子操作与原子操作的组合，并不一定是原子操作，例如存在竞态条件。</h3></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">dtyy</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://dtyytop.gitee.io/2020/04/15/devnotes/zhi-mian-java/bing-fa/bing-fa-he-xin/2.1-java-nei-cun-mo-xing-yu-san-da-te-xing/">https://dtyytop.gitee.io/2020/04/15/devnotes/zhi-mian-java/bing-fa/bing-fa-he-xin/2.1-java-nei-cun-mo-xing-yu-san-da-te-xing/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://dtyytop.gitee.io" target="_blank">Reality</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/JMM/">JMM</a></div><div class="post_share"><div class="social-share" data-image="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222621.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001034.png" target="_blank"><img class="post-qr-code-img" src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001034.png" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li><li class="reward-item"><a href="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001009.png" target="_blank"><img class="post-qr-code-img" src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001009.png" alt="alipay"/></a><div class="post-qr-code-desc">alipay</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="next-post pull-full"><a href="/2020/04/15/devnotes/zhi-mian-java/bing-fa/bing-fa-he-xin/1.6-thread-lei-de-chong-yao-fang-fa/"><img class="next-cover" src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222634.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Thread类重要方法</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">dtyy</div><div class="author-info__description">Java全栈</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">95</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/dtyytop"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/dtyytop" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:1607961042@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Java%E5%86%85%E5%AD%98%E6%A8%A1%E5%9E%8B"><span class="toc-number">1.</span> <span class="toc-text">Java内存模型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%95%E4%B8%BA%E5%BA%95%E5%B1%82%E5%8E%9F%E7%90%86%EF%BC%9F"><span class="toc-number">1.1.</span> <span class="toc-text">何为底层原理？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E9%9C%80%E8%A6%81JMM%EF%BC%8C%E4%BB%80%E4%B9%88%E6%98%AFJMM"><span class="toc-number">1.2.</span> <span class="toc-text">为什么需要JMM，什么是JMM</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A6%82%E5%BF%B5%E5%8C%BA%E5%88%86%EF%BC%9AJVM%E5%86%85%E5%AD%98%E7%BB%93%E6%9E%84%E3%80%81JMM%E3%80%81Java%E5%AF%B9%E8%B1%A1%E6%A8%A1%E5%9E%8B"><span class="toc-number">1.3.</span> <span class="toc-text">概念区分：JVM内存结构、JMM、Java对象模型</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%87%8D%E6%8E%92%E5%BA%8F"><span class="toc-number">2.</span> <span class="toc-text">重排序</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%87%8D%E6%8E%92%E5%BA%8F%E6%A1%88%E4%BE%8B%E6%BC%94%E7%A4%BA"><span class="toc-number">2.1.</span> <span class="toc-text">重排序案例演示</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%87%8D%E6%8E%92%E5%BA%8F%E7%9A%84%E5%A5%BD%E5%A4%84"><span class="toc-number">2.2.</span> <span class="toc-text">重排序的好处</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%87%8D%E6%8E%92%E5%BA%8F%E7%9A%843%E7%A7%8D%E6%83%85%E5%86%B5"><span class="toc-number">2.3.</span> <span class="toc-text">重排序的3种情况</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%AF%E8%A7%81%E6%80%A7"><span class="toc-number">3.</span> <span class="toc-text">可见性</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%AF%E8%A7%81%E6%80%A7%E6%BC%94%E7%A4%BA%E6%A1%88%E4%BE%8B"><span class="toc-number">3.1.</span> <span class="toc-text">可见性演示案例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E6%9C%89%E5%8F%AF%E8%A7%81%E6%80%A7%E9%97%AE%E9%A2%98"><span class="toc-number">3.2.</span> <span class="toc-text">为什么有可见性问题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BF%9D%E8%AF%81%E5%8F%AF%E8%A7%81%E6%80%A7%E7%9A%84%E6%8E%AA%E6%96%BD"><span class="toc-number">3.3.</span> <span class="toc-text">保证可见性的措施</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JMM%E7%9A%84%E6%8A%BD%E8%B1%A1"><span class="toc-number">4.</span> <span class="toc-text">JMM的抽象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%93%8D%E4%BD%9C%E5%AF%B9%E8%B1%A1%E2%80%93%E5%85%B1%E4%BA%AB%E5%8F%98%E9%87%8F"><span class="toc-number">4.1.</span> <span class="toc-text">操作对象–共享变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E6%9C%AC%E5%9C%B0%E5%86%85%E5%AD%98"><span class="toc-number">4.2.</span> <span class="toc-text">什么是本地内存</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BB%E5%86%85%E5%AD%98%E5%92%8C%E6%9C%AC%E5%9C%B0%E5%86%85%E5%AD%98%E7%9A%84%E5%85%B3%E7%B3%BB"><span class="toc-number">4.3.</span> <span class="toc-text">主内存和本地内存的关系</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%86%85%E5%AD%98%E4%BA%A4%E4%BA%92%E6%93%8D%E4%BD%9C%EF%BC%88%E4%BA%86%E8%A7%A3%EF%BC%89"><span class="toc-number">4.4.</span> <span class="toc-text">内存交互操作（了解）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#happens-before%E5%8E%9F%E5%88%99"><span class="toc-number">4.5.</span> <span class="toc-text">happens-before原则</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%B7%E4%BD%93%E5%8E%9F%E5%88%99%EF%BC%88%E5%85%88%E5%8F%91%E7%94%9F%EF%BC%8C%E5%8F%AF%E8%A7%81%EF%BC%89"><span class="toc-number">4.5.1.</span> <span class="toc-text">具体原则（先发生，可见）</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8E%9F%E5%AD%90%E6%80%A7"><span class="toc-number">5.</span> <span class="toc-text">原子性</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#java%E4%B8%AD%E7%9A%84%E5%8E%9F%E5%AD%90%E6%93%8D%E4%BD%9C%E6%9C%89%E5%93%AA%E4%BA%9B%EF%BC%9F"><span class="toc-number">5.1.</span> <span class="toc-text">java中的原子操作有哪些？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#long%E5%92%8Cdouble%E7%9A%84%E5%8E%9F%E5%AD%90%E6%80%A7"><span class="toc-number">5.2.</span> <span class="toc-text">long和double的原子性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8E%9F%E5%AD%90%E6%93%8D%E4%BD%9C%E4%B8%8E%E5%8E%9F%E5%AD%90%E6%93%8D%E4%BD%9C%E7%9A%84%E7%BB%84%E5%90%88%EF%BC%8C%E5%B9%B6%E4%B8%8D%E4%B8%80%E5%AE%9A%E6%98%AF%E5%8E%9F%E5%AD%90%E6%93%8D%E4%BD%9C%EF%BC%8C%E4%BE%8B%E5%A6%82%E5%AD%98%E5%9C%A8%E7%AB%9E%E6%80%81%E6%9D%A1%E4%BB%B6%E3%80%82"><span class="toc-number">5.3.</span> <span class="toc-text">原子操作与原子操作的组合，并不一定是原子操作，例如存在竞态条件。</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.3-nginx-jin-cheng-mo-xing-yu-shi-jian-chu-li-ji-zhi/" title="Nginx进程模型"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222600.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Nginx进程模型"/></a><div class="content"><a class="title" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.3-nginx-jin-cheng-mo-xing-yu-shi-jian-chu-li-ji-zhi/" title="Nginx进程模型">Nginx进程模型</a><time datetime="2021-06-01T16:00:00.000Z" title="发表于 2021-06-02 00:00:00">2021-06-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.4-nginx-he-xin-wen-jian-jie-gou-fen-xi/" title="Nginx核心配置结构"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Nginx核心配置结构"/></a><div class="content"><a class="title" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.4-nginx-he-xin-wen-jian-jie-gou-fen-xi/" title="Nginx核心配置结构">Nginx核心配置结构</a><time datetime="2021-06-01T16:00:00.000Z" title="发表于 2021-06-02 00:00:00">2021-06-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/nginx/1.2-wei-shi-me-xuan-ze-nginx/" title="集群、代理与Nginx"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="集群、代理与Nginx"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/nginx/1.2-wei-shi-me-xuan-ze-nginx/" title="集群、代理与Nginx">集群、代理与Nginx</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-zhu-cong-fu-zhi-yu-yuan-li/" title="Redis主从复制架构与原理"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222646.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Redis主从复制架构与原理"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-zhu-cong-fu-zhi-yu-yuan-li/" title="Redis主从复制架构与原理">Redis主从复制架构与原理</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-chi-jiu-hua-ji-zhi/" title="Redis的两种持久化机制"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222634.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Redis的两种持久化机制"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-chi-jiu-hua-ji-zhi/" title="Redis的两种持久化机制">Redis的两种持久化机制</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222621.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By dtyy</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="false"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>